<template>
  <div>
    <el-form ref="form" label-width="80px">
      <el-form-item label="礼品名称">
        <el-input v-model="giftlist.name" style="width: 540px"></el-input>
      </el-form-item>

      <el-form-item label="所需乐豆">
        <el-input v-model="giftlist.integral" style="width: 540px" type="number"></el-input>
      </el-form-item>

      <el-form-item label="礼品货储">
        <el-input v-model="giftlist.number" style="width: 540px" type="number"></el-input>
      </el-form-item>

      <el-form-item label="礼品图片">
        <!-- 预览图片用 -->
        <img :src="valueUrl" style="width: 240px" />
      </el-form-item>

      <el-upload
        class="upload-demo"
        action="http://localhost:3000/gift/upload"
        :on-success="uploadSuccess"
        :show-file-list="false"
      >
        <el-button size="small" type="primary">更换图片</el-button>
      </el-upload>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">更新</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { fetchById, update } from "@/api/gift";
export default {
  data() {
    return {
      valueUrl: "",
      giftlist: {},
      newgiftlist: {},
    };
  },
  created() {
    fetchById({
      id: this.$route.params.id,
    }).then((res) => {
      console.log(res.data[0]);
      this.giftlist = res.data[0];
      this.valueUrl = res.data[0].download_url;
    });
  },
  methods: {
    uploadSuccess(res) {
      console.log(res);
      console.log(res.id_list.file_list.length);
      if (res.id_list.file_list.length > 0) {
        this.valueUrl = res.id_list.file_list[0].download_url;
        this.newgiftlist.newfileid = res.id_list.file_list[0].fileid;
        this.$message({
          message: "上传成功",
          type: "success",
        });
      }
    },

    onSubmit() {
      this.newgiftlist._id = this.giftlist._id;
      this.newgiftlist.name = this.giftlist.name;
      this.newgiftlist.integral = this.giftlist.integral;
      this.newgiftlist.number = this.giftlist.number;
      this.newgiftlist.fileid = this.giftlist.fileid;
      update(this.newgiftlist).then((res) => {
        console.log(res);
        if (res.data.modified > 0) {
          this.$message({
            message: "更新成功",
            type: "success",
          });
        } else {
          this.$message.error("更新失败");
        }
        this.$router.push("/gift/list");
      });
    },
    onCancel() {
      this.$router.push("/gift/list");
    },
  },
};
</script>

<style scoped>
</style>



